package com.example.component;

import com.example.constant.TimerEnum;
import com.example.pojo.vo.TimerVo;
import com.example.tools.RedisTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2018/11/23
 * @Description: 初始化定时器
 **/
@Slf4j
@Component
public class InitTimer {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    public void init() {
        threadPoolTaskScheduler.shutdown();
        threadPoolTaskScheduler.initialize();
        List<TimerVo> lists = RedisTools.hget(stringRedisTemplate, TimerEnum.TIMER_LIST.getKey(), TimerVo.class);
        lists.forEach(timerVo -> saveScheduler(timerVo));
    }

    public void saveScheduler(TimerVo timerVo){
        if(timerVo.getStatus()==1){
            log.info("新增定时器 --> {}",timerVo.getName());
            threadPoolTaskScheduler.schedule(() -> {
                log.info("定时器请求 --> {}",timerVo.getUri());
//                restTemplate.getForObject(timerVo.getUri(),String.class);
            }, new CronTrigger(timerVo.getCron()));
        }
    }

}
